package com.macro.mall.service.impl;


import com.macro.mall.dto.UmsPermissionNode;
import com.macro.mall.service.UmsPermissionService;
import com.macro.mapper.UmsPermissionMapper;
import com.macro.model.UmsPermission;
import com.macro.model.UmsPermissionExample;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UmsPermissionServiceImpl implements UmsPermissionService {

    @Autowired
    private UmsPermissionMapper permissionMapper;


    @Override
    public int create(UmsPermission permission) {
        permission.setCreateTime(new Date());
        return permissionMapper.insert(permission);
    }

    @Override
    public int update(Long id, UmsPermission permission) {
        permission.setId(id);
        return permissionMapper.updateByPrimaryKey(permission);
    }

    @Override
    public int delete(List<Long> ids) {
       UmsPermissionExample example = new UmsPermissionExample();
       example.createCriteria().andIdIn(ids);

       return permissionMapper.deleteByExample(example);
    }

    @Override
    public List<UmsPermission> list() {
        return permissionMapper.selectByExample(new UmsPermissionExample());
    }

    @Override
    public List<UmsPermissionNode> treeList() {
        List<UmsPermission> permissions = list();
        List<UmsPermissionNode> nodes = permissions.stream().filter(permission -> permission.getPid().equals(0L))
                .map(permission -> convertPermissionNode(permission, permissions))
                .collect(Collectors.toList());
        return nodes;
    }

    private UmsPermissionNode convertPermissionNode(UmsPermission permission, List<UmsPermission> permissions) {
        UmsPermissionNode node = new UmsPermissionNode();
        BeanUtils.copyProperties(permission,node);
        List<UmsPermissionNode> children = permissions.stream()
                .filter(sub -> sub.getPid().equals(permission.getId()))
                .map(sub -> convertPermissionNode(sub,permissions))
                .collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
}
